import { HttpClient, HttpParams } from '@angular/common/http';
import { Component, Injectable, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import {
  memberConditionUrl,
  addMemberUrl,
  applicationForm,
  glanceOverimageUrl
} from '../../../urlConfig';
import { HttpService } from '../../../service/httpService/http.service';
import * as XLSX from 'xlsx';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { LocalStorageService } from '../../../service/localStorageService/local-storage.service';
@Injectable()
export class RandomUserService {
  getUsers(
    pageIndex: number = 1,
    pageSize: number = 10,
    sortField: string,
    sortOrder: string,
    genders: string[]
  ): Observable<{}> {
    let params = new HttpParams()
      .append('page', `${pageIndex}`)
      .append('results', `${pageSize}`)
      .append('sortField', sortField)
      .append('sortOrder', sortOrder);
    genders.forEach(gender => {
      params = params.append('gender', gender);
    });

    return this.http.get(`${applicationForm}`, {
      params
    });
  }
  constructor(
    private http: HttpClient,
    public localStorage: LocalStorageService
  ) {}
}

@Component({
  selector: 'app-member-application',
  templateUrl: './member-application.component.html',
  styleUrls: ['./member-application.component.styl'],
  providers: [RandomUserService]
})
export class MemberApplicationComponent {
  mapOfExpandData: { [key: string]: boolean } = {};
  nzPageSize = 10; // 每页显示多少数据
  pageIndex = 1;
  pageSize = 20;
  total = 1;
  listOfData = []; // 存放被渲染的全部数据
  getData = []; // 存放接口获取到的数据
  loading = true; // 控制加载动画
  sortValue: string | null = null; // 从大到小 或 从小到大 排序
  sortKey: string | null = null; //要筛选的字段
  filterGender = [
    { text: 'male', value: 'male' },
    { text: 'female', value: 'female' }
  ];
  searchGenderList: string[] = [];
  firstTrialArray: any = []; // 存放通过初审的数据
  deleteTrialArray: any = []; // 存放被暂时判定为初审不通过的数据
  notAuditedArray: any = []; // 存放未审核的数据
  token: any = this.localStorage.getItem('token');
  xlsxData: any = []; // 要导出的表单
  imageUrl: string = glanceOverimageUrl; // 存放浏览图片的前缀地址
  imgpreview:''; // 存放预览图片的地址

  constructor(
    private randomUserService: RandomUserService,
    public http: HttpService,
    private message: NzMessageService,
    public localStorage: LocalStorageService,
    private router: Router
  ) {}

  ngOnInit(): void {
    this.searchData();
  }

  // 对表单排序
  sort(sort: { key: string; value: string }): void {
    this.sortKey = sort.key;
    this.sortValue = sort.value;
    if (this.sortValue === 'descend') {
      this.descend();
    } else {
      this.ascend();
    }
  }

  // 获取后台数据
  searchData(reset: boolean = false): void {
    if (reset) {
      this.pageIndex = 1;
    }
    this.loading = true;
    this.randomUserService
      .getUsers(
        this.pageIndex,
        this.pageSize,
        this.sortKey!,
        this.sortValue!,
        this.searchGenderList
      )
      .subscribe((event: any) => {
        console.log(event);
        if (event.code === 200) {
          this.loading = false;
          this.total = 200;
          this.listOfData = event.data;
          this.arrayMap();
        }
      });
  }

  //初审不通过
  deleteTrial(username: string): void {
    var data: object = {
      state: 2, // 不通过初审
      accessToken: this.token.accessToken
    };
    this.http
      .putData(memberConditionUrl + username, data)
      .subscribe((event: any) => {
        console.log(event);

        if (event.code === 200) {
          this.searchData();
        }
      });
  }

  // 通过初审
  firstTrial(username: string) {
    var data: object = {
      state: 1,
      accessToken: this.token.accessToken
    };
    this.http
      .putData(memberConditionUrl + username, data)
      .subscribe((event: any) => {
        if (event.code === 200) {
          this.searchData();
        }
      });
  }

  // 成为正式成员，删除该申请信息
  addMember(username: string) {
    this.http
      .postData(addMemberUrl, { username, accessToken: this.token.accessToken })
      .subscribe((event: any) => {
        if (event.code === 200) {
          this.listOfData = this.listOfData.filter(
            d => d.username !== username
          );
        } else if (event.code === 201) {
          this.createMessage('error');
        }
      });
  }

  // 升序
  ascend() {
    this.concatarray(0);
  }

  // 降序
  descend() {
    this.concatarray(1);
  }

  // 替换state字段描述
  arrayMap() {
    var maps = new Map([[0, '未审核'], [1, '通过初审'], [2, '未通过初审']]);
    this.listOfData = this.listOfData.map(event => {
      event.state = maps.get(event.state);
      return event;
    });
  }

  //
  concatarray(sorts: number) {
    this.getDataFun(sorts);
  }

  getDataFun(sorts) {
    this.randomUserService
      .getUsers(
        this.pageIndex,
        this.pageSize,
        this.sortKey!,
        this.sortValue!,
        this.searchGenderList
      )
      .subscribe((dataobj: any) => {
        this.total = 200;
        this.getData = dataobj.data;
        this.firstTrialArray = this.getData.filter(event => event.state === 1);
        this.deleteTrialArray = this.getData.filter(event => event.state === 2);
        this.notAuditedArray = this.getData.filter(event => event.state === 0);
        if (sorts === 0) {
          this.listOfData = this.notAuditedArray.concat(
            this.firstTrialArray,
            this.deleteTrialArray
          );
        } else if (sorts === 1) {
          this.listOfData = this.firstTrialArray.concat(
            this.notAuditedArray,
            this.deleteTrialArray
          );
        }
        this.arrayMap();
      });
  }

  // 导出通过初审的名单
  deriveXlsx() {
    this.randomUserService
      .getUsers(
        this.pageIndex,
        this.pageSize,
        this.sortKey!,
        this.sortValue!,
        this.searchGenderList
      )
      .subscribe((dataobj: any) => {
        this.total = 200;
        dataobj.data.forEach((event: any) => {
          if (event.state === 1) { // 1 表示通过初审的成员
            this.xlsxData.push({
              name: event.name,
              phoneNumber: event.phoneNumber
            });
          }
        });

        var ws = XLSX.utils.json_to_sheet(this.xlsxData);

        // /* add to workbook */
        var wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Presidents');

        /* write workbook and force a download */
        XLSX.writeFile(wb, '通过初审表单.xlsx');
      });
  }

    // 预览图片
    preview(memberImgurl,imgname){
      this.imgpreview = memberImgurl + imgname;
      const element = document.getElementById('imgpreviewbox');
      element.style.display = 'block';
    }
   
    // 关闭预览
    imgicon(){
      const element = document.getElementById('imgpreviewbox');
      element.style.display = 'none';
    }

  // 全局提示
  createMessage(type: string): void {
    this.message.create(type, `该成员还未通过初审，不能加入正式成员！`);
  }
}
